//
//  HRMainRootView.m
//  Hear
//
//  Created by mac on 2017/3/23.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRMainRootView.h"
#import "HRVoiceSliderView.h"
//#import "MyPlayTool.h"
#import "UIImage+BlurEffects.h"
@interface HRMainRootView ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate,VoiceSliderViewDelegate>
@property (nonatomic, strong)UIImageView *backImageView;
@property (nonatomic, strong)UICollectionView *collectionView;
@property (nonatomic, strong)UIImageView *pipingImageView;
@property (nonatomic, assign)BOOL isUpward;
@property (nonatomic, strong)HRVoiceCardCell *tempCurrentCell;
@property (nonatomic, assign)CGFloat tempOffsetX;
@property (nonatomic, strong)HRVoiceCardCell *cashCurrentCell;
@property (nonatomic, strong)NSArray *contentArr;
@property (nonatomic, strong)HRVoiceSliderView *sliderView;

@property (nonatomic, assign)BOOL isReload;
@property (nonatomic, strong)UIButton *recordButton;


@property (nonatomic, assign)CGFloat currentOffsetX;


@end
@implementation HRMainRootView

- (void)recordButtonClick{
    if (self.recordButtonClickBlock){
        self.recordButtonClickBlock();
    }
}

-(UIButton *)recordButton{
    if (_recordButton == nil){
        UIButton *recordButton = [UIButton buttonWithType:0];
        [recordButton setImage:[UIImage imageNamed:@"录音"] forState:0];
        [recordButton addTarget:self action:@selector(recordButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:(self.recordButton = recordButton)];
        CGFloat pading;
        if ([self checkDevice:@"iPad"]){
            pading = 0;
        }else{
            pading = -20;
        }
        WeakSelf
        [recordButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(weakSelf).offset(60);
            make.bottom.equalTo(weakSelf.sliderView.mas_top).offset(adjuctFloat(pading));
            make.size.mas_equalTo(CGSizeMake(adjuctFloat(50), adjuctFloat(50)));
        }];
    }
    return _recordButton;
}


-(UIButton *)playButton{
    if (_playButton == nil){
        UIButton *playButton = [UIButton buttonWithType:0];
        [playButton setImage:[UIImage imageNamed:@"暂停键"] forState:UIControlStateNormal];
        [playButton addTarget:self action:@selector(playButtonClick) forControlEvents:UIControlEventTouchUpInside];
        playButton.selected = YES;
        _playButton = playButton;
        [self addSubview:playButton];
        
        CGFloat pading;
        if ([self checkDevice:@"iPad"]){
            pading = 0;
        }else{
            pading = -20;
        }
        
        WeakSelf
        [playButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(weakSelf).offset(-60);
            make.bottom.equalTo(weakSelf.sliderView.mas_top).offset(adjuctFloat(pading));
            make.size.mas_equalTo(CGSizeMake(adjuctFloat(50), adjuctFloat(50)));
        }];
    }
    return _playButton;
}

-(bool)checkDevice:(NSString*)name
{
    NSString* deviceType = [UIDevice currentDevice].model;
    DDLog(@"deviceType = %@", deviceType);
    NSRange range = [deviceType rangeOfString:name];
    return range.location != NSNotFound;
}

-(HRVoiceSliderView *)sliderView
{
    if (_sliderView == nil)
    {
        _sliderView = [HRVoiceSliderView new];
        _sliderView.delegate = self;
        [self addSubview:self.sliderView];
        WeakSelf
        [self.sliderView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(weakSelf.mas_bottom).offset(-adjuctFloat(20+49));
            make.left.width.equalTo(weakSelf);
            make.height.mas_equalTo(adjuctFloat(30));
        }];
    }
    return _sliderView;
}


- (UIImage *)changeImage:(NSString *)imageName andTintColor:(UIColor *)color{
    CGFloat blurRadius = 20.f;
    CGFloat saturationDeltaFactor = 1.0f;
    UIColor *tintColor = color;
     return  [UIImage ty_imageByApplyingBlurToImage:[UIImage imageNamed:imageName] withRadius:blurRadius tintColor:[tintColor colorWithAlphaComponent:0.5] saturationDeltaFactor:saturationDeltaFactor maskImage:nil];
}

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {

        
        self.contentArr = [NSArray array];

        self.backImageView = [UIImageView new];
        self.backImageView.image = [UIImage imageNamed:@"主页背景图"];
        [self addSubview:self.backImageView];

        
        [self loadCardView];
        
        [self addSubview:self.sliderView];
        [self addSubview:self.playButton];
        [self addSubview:self.recordButton];
        
        
        UIImageView *topImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"圆形尾巴半圆"]];
        topImageView.contentMode = UIViewContentModeScaleAspectFill;
        [self addSubview:topImageView];
        
        
        UIImageView *pipingImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"探针管道"]];
        pipingImageView.contentMode = UIViewContentModeScaleAspectFill;
        [self insertSubview:(self.pipingImageView = pipingImageView) belowSubview:topImageView];
        
        
        CALayer *layer = [pipingImageView layer];
        layer.anchorPoint = CGPointMake(0, 0);
        
        WeakSelf
        [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(0);
        }];

        
        [topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(weakSelf);
            make.top.equalTo(weakSelf.backImageView).offset(kTopHeight);
            make.size.mas_equalTo(CGSizeMake(adjuctFloat(65), adjuctFloat(35)));
         }];
        
        [pipingImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(topImageView.mas_bottom).offset(-adjuctFloat(105));
            make.centerX.equalTo(weakSelf).offset(adjuctFloat(10));
            make.size.mas_equalTo(CGSizeMake(adjuctFloat(80), adjuctFloat(180)));
        }];
        
        
    }
    return self;
}


- (void)loadCardView
{
    _collectionView = ({

        
        
        
        
        UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
        layout.itemSize = CGSizeMake(kFullWidth, kFullWidth);
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = 0;
        
        UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.frame collectionViewLayout:layout];
        collectionView.backgroundColor = [UIColor clearColor];
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.scrollsToTop = NO;
        collectionView.showsVerticalScrollIndicator = NO;
        collectionView.showsHorizontalScrollIndicator = NO;
        collectionView.pagingEnabled = YES;
        [collectionView registerClass:[HRVoiceCardCell class] forCellWithReuseIdentifier:@"HRVoiceCardCell"];
        [self addSubview:collectionView];
        WeakSelf
        
        
        [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(kFullWidth, kFullWidth));
            make.center.equalTo(weakSelf);
        }];
        

        
        collectionView;
        
        
        
        
    });
}


#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.contentArr.count;
}


- ( UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    HRVoiceCardCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HRVoiceCardCell" forIndexPath:indexPath];
    cell.mainModel = self.contentArr[indexPath.row];
    WeakSelf
    cell.lookInfoClickBlock = ^(){
        if (weakSelf.lookInfoClickBlock){
            weakSelf.lookInfoClickBlock(self.contentArr[indexPath.row]);
        }
    };
    return cell;
}



-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.hideLeftMenuBlock){
        self.hideLeftMenuBlock();
    }
    
    DDLog(@"%f",scrollView.contentOffset.x);
    if (self.currentOffsetX > scrollView.contentOffset.x){
        self.collectionView.contentOffset = CGPointMake(self.tempOffsetX, scrollView.contentOffset.y);
        return;
    }
    [self setupOffsetChange:scrollView.contentOffset.x];
    if (scrollView.contentOffset.x <= 0){
        self.currentOffsetX = 0;
    }
}


-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.isReload = NO;
}


-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.currentOffsetX = scrollView.contentOffset.x;

    
    if (!self.isReload){
        if (scrollView.contentOffset.x<= 0)return;
        if (self.loadNewContentBlock){
            self.loadNewContentBlock();
        }
    }
    
}


#pragma mark - UICollectionViewDelegateFlowLayout

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.tempCurrentCell = (HRVoiceCardCell *)cell;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    self.isReload = YES;
    self.currentCell = (HRVoiceCardCell *)cell;
    if (indexPath.row == 0)
    {
        if (!self.isFirstTransfrom)
        {
//            HRMainRootModel*model = self.contentArr[indexPath.row];
//            self.backImageView.image = [self changeImage:model.UserPictureName andTintColor:[UIColor colorWithHexString:model.UserPictureBackgroundColor]];

            self.cashCurrentCell = self.currentCell;
            self.isFirstTransfrom = YES;
            [self.currentCell startTransformAnimation];
            
            self.playButton.selected = YES;
            [self playButtonClick];
        }
        
    }
    [(HRVoiceCardCell *)cell configureCellWithPostURL:@"唱片"];
}



- (void)setupOffsetChange:(CGFloat)offSetX
{
    if (offSetX == 0)
    {
        
        [self tramsformAnimation:0];
        if (offSetX == self.tempOffsetX)
        {
            [self.cashCurrentCell stopTransformAnimation];
            [self.cashCurrentCell startTransformAnimation];
        }else{
            [self.cashCurrentCell stopTransformAnimation];
            self.cashCurrentCell = self.currentCell;
            [self.tempCurrentCell stopTransformAnimation];
            [self.currentCell startTransformAnimation];
            self.sliderView.mainModel = self.currentCell.mainModel;
//            self.backImageView.image = [self changeImage:self.currentCell.mainModel.UserPictureName andTintColor:[UIColor colorWithHexString:self.currentCell.mainModel.UserPictureBackgroundColor]];


        }
        self.tempOffsetX = offSetX;
    }else if(offSetX/kFullWidth == (int)(offSetX/kFullWidth))
    {
        
        if (offSetX == self.tempOffsetX)
        {
            [self.cashCurrentCell stopTransformAnimation];
            [self.cashCurrentCell startTransformAnimation];
        }else{
            if (!self.playButton.selected){
                self.playButton.selected = YES;
                [self.playButton setImage:[UIImage imageNamed:@"暂停键"] forState:UIControlStateNormal];
            }
            [self saveSoundRecord];
            [self.cashCurrentCell stopTransformAnimation];
            self.cashCurrentCell = self.currentCell;
            [self.tempCurrentCell stopTransformAnimation];
            [self.currentCell startTransformAnimation];
            self.sliderView.mainModel = self.currentCell.mainModel;
//            self.backImageView.image = [self changeImage:self.currentCell.mainModel.UserPictureName andTintColor:[UIColor colorWithHexString:self.currentCell.mainModel.UserPictureBackgroundColor]];

        }
        self.tempOffsetX = offSetX;

        //DDLog(@"整>>>>>%f>>>>%f>>>>>%d",scrollView.contentOffset.x,offSetX/kFullWidth,(int)(offSetX/kFullWidth));
        
        [self tramsformAnimation:0];
    }else{
        [self.cashCurrentCell stopTransformAnimation];
        [self.currentCell stopTransformAnimation];
        [self.tempCurrentCell stopTransformAnimation];
        if (self.isUpward)
            return;
        self.isUpward = YES;
        [self tramsformAnimation:-M_PI/6.0];
        //DDLog(@"语>>>>>%f",scrollView.contentOffset.x);
        
    }
}

- (void)tramsformAnimation:(CGFloat)angle
{
    
    CGAffineTransform  transform;
    
    //设置旋转度数
    
    transform = CGAffineTransformMakeRotation(angle);
    WeakSelf
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.pipingImageView.transform = transform;
    } completion:^(BOOL finished) {
        if (angle >= 0)
        {
            self.isUpward = NO;
        }
        
    }];
}

-(void)setGetDataArr:(NSArray *)getDataArr
{
//    self.sliderView.mainModel = [getDataArr firstObject];
    [self.sliderView emptySlider];
    self.contentArr = getDataArr;
    [self.collectionView reloadData];
}

#pragma 播放
- (void)playButtonClick{
    if (self.playButton.selected){
        self.playButton.selected = NO;
//        [[MyPlayTool sharePlayTool] pause];
        [self.playButton setImage:[UIImage imageNamed:@"播放"] forState:UIControlStateNormal];
//        self.isLoadSound = YES;

        [self.cashCurrentCell stopTransformAnimation];
        [self.currentCell stopTransformAnimation];
        [self.tempCurrentCell stopTransformAnimation];
    }else{
        self.playButton.selected = YES;
        [self.playButton setImage:[UIImage imageNamed:@"暂停键"] forState:UIControlStateNormal];
        self.sliderView.mainModel = self.currentCell.mainModel;
//        if (!self.isLoadSound){
//            self.isLoadSound = NO;
//            self.sliderView.mainModel = self.currentCell.mainModel;
//        }else{
//            [MyPlayTool sharePlayTool].soundModel = self.currentCell.mainModel;
//
//            [[MyPlayTool sharePlayTool] play];
//        }
        [self.cashCurrentCell stopTransformAnimation];
        self.cashCurrentCell = self.currentCell;
        [self.tempCurrentCell stopTransformAnimation];
        [self.currentCell startTransformAnimation];
       
        
    }
}


- (void)saveSoundRecord{
    if (self.delegate){
        [self.delegate saveSoundRecordVisitedUserLocalId:self.currentCell.mainModel.UserLocalId andSoundUrl:self.currentCell.mainModel.SoundUrl];
    }
}



#pragma VoiceSliderViewDelegate
- (void)startPlaySound{
    
}
- (void)stopPlaySound{
    self.isLoadSound = NO;
    [self.playButton setImage:[UIImage imageNamed:@"播放"] forState:UIControlStateNormal];
    self.playButton.selected = NO;
    [self.cashCurrentCell stopTransformAnimation];
    [self.currentCell stopTransformAnimation];
    [self.tempCurrentCell stopTransformAnimation];
}

@end
